package controllers

import (
	"demochat/jwt"
	"demochat/models"
	"demochat/utils"
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	beego "github.com/beego/beego/v2/server/web"
	jwt2 "github.com/dgrijalva/jwt-go/v4"
	"time"
)

type LoginController struct {
	beego.Controller
	//BaseController
}

func (c *LoginController) Get() {
	c.Data["Website"] = "beego.vip"
	c.Data["Email"] = "astaxie@gmail.com"
	c.TplName = "index.tpl"
}

func (c *LoginController) Login() {
	c.TplName = "login.html"
}

func (c *LoginController) UserLogin() {
	username := c.GetString("username")
	password := c.GetString("password")
	logs.Info(username)
	logs.Info(password)
	err, u := models.Insert(username, password)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 202,
			"msg":  err.Error(),
		}
		c.ServeJSON()
	}
	token, err := jwt.CreateJwt(&jwt.MyCustomClaims{
		UserId: u.Id,
		StandardClaims: jwt2.StandardClaims{
			//过期时间
			ExpiresAt: jwt2.NewTime(float64(time.Now().Unix() + 86400)),
		},
	})
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 202,
			"msg":  err.Error(),
		}
		c.ServeJSON()

	}
	key := "login:" + fmt.Sprintf("%v", username)
	err = utils.RedisSet(key)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 202,
			"msg":  err.Error(),
		}
		c.ServeJSON()
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "Login success",
		"data": map[string]interface{}{
			"toke": token,
		},
	}
	c.ServeJSON()
}

// Vifi token验证
func (c *LoginController) Vifi() {
	tk := c.GetString("tk")
	id, err := jwt.VerificationTk(tk)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 202,
			"msg":  err.Error(),
		}
		c.ServeJSON()
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "Login success",
		"data": map[string]interface{}{
			"用户ID": id,
		},
	}
	c.ServeJSON()
}
